#include <51func.h>
typedef struct shareRes_s {
    int tickets;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
} shareRes_t;
void *sellWindow1(void *arg){
    shareRes_t * pshareRes = (shareRes_t *)arg; 
    while(1){
        pthread_mutex_lock(&pshareRes->mutex);
        if(pshareRes->tickets <= 0){
            pthread_mutex_unlock(&pshareRes->mutex);
            break;
        }
        printf("before window 1, tickets = %d\n", pshareRes->tickets);
        --pshareRes->tickets;
        printf("after window 1, tickets = %d\n", pshareRes->tickets);
        if(pshareRes->tickets < 10){
            pthread_cond_signal(&pshareRes->cond);
        }
        pthread_mutex_unlock(&pshareRes->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}
void *sellWindow2(void *arg){
    shareRes_t * pshareRes = (shareRes_t *)arg; 
    while(1){
        pthread_mutex_lock(&pshareRes->mutex);
        if(pshareRes->tickets <= 0){
            pthread_mutex_unlock(&pshareRes->mutex);
            break;
        }
        printf("before window 2, tickets = %d\n", pshareRes->tickets);
        --pshareRes->tickets;
        printf("after window 2, tickets = %d\n", pshareRes->tickets);
        if(pshareRes->tickets < 10){
            pthread_cond_signal(&pshareRes->cond);
        }
        pthread_mutex_unlock(&pshareRes->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}
void *addTickets(void *arg){
    shareRes_t * pshareRes = (shareRes_t *)arg; 
    pthread_mutex_lock(&pshareRes->mutex);
    if(pshareRes->tickets > 10){
        printf("tickets is enough now !\n");
        pthread_cond_wait(&pshareRes->cond,&pshareRes->mutex);
    }
    printf("tickets is not enough now !\n");
    pshareRes->tickets += 10; //加票业务需要带锁运行
    pthread_mutex_unlock(&pshareRes->mutex);
    pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
    shareRes_t shareRes;
    shareRes.tickets = 20;
    pthread_mutex_init(&shareRes.mutex,NULL);
    pthread_cond_init(&shareRes.cond,NULL);
    pthread_t tid1,tid2,tid3;
    pthread_create(&tid1,NULL,sellWindow1,&shareRes);
    pthread_create(&tid2,NULL,sellWindow2,&shareRes);
    pthread_create(&tid3,NULL,addTickets,&shareRes);
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);
    return 0;
}

